<template>
    <div class="warehouse-container">
        <div class="warehouse-card">
            <el-row>
                <el-col :span="24">
                    <el-breadcrumb separator-class="el-icon-arrow-right">
                        <el-breadcrumb-item :to="{ path: '/warehouseList' }">仓库管理</el-breadcrumb-item>
                        <el-breadcrumb-item>仓库详情</el-breadcrumb-item>
                    </el-breadcrumb>
                </el-col>
            </el-row>

            <div class="section-title">基本信息</div>
            <el-form ref="form" :model="warehouseDetail" label-width="80px">
                <el-form-item label="仓库名称">
                    <el-input placeholder="仓库名称" v-model="warehouseDetail.name"></el-input>
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="所在城市">
                            <el-select v-model="warehouseDetail.cityId" @change="handleCityChange" placeholder="请选择">
                                <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="所在区域">
                            <el-select v-model="warehouseDetail.districtId" placeholder="请选择">
                                <el-option v-for="item in districtOptions" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="仓库面积">
                            <el-input placeholder="请输入面积" v-model="warehouseDetail.area">
                                <template slot="append">m²</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="仓库地址">
                    <el-input type="textarea" :rows="4" placeholder="请输入详细地址" v-model="warehouseDetail.address"></el-input>
                </el-form-item>
            </el-form>
        </div>

        <!-- 骑手管理部分 -->
        <div class="warehouse-card">
            <div class="section-title">骑手管理</div>
            <el-form ref="selectedCourier" :model="selectedCourier" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="配置骑手">
                            <el-input placeholder="请输入骑手的姓名" v-model="selectedCourier.riderName">
                                <el-button slot="append" type="primary" @click="queryRiderByName">查询</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="text-right">
                        <el-button type="success" @click="dialogFormVisible = true">
                            <i class="el-icon-plus"></i> 新增骑手
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>

            <el-table :data="addRiderList" border stripe>
                <el-table-column prop="courierName" label="骑手姓名"></el-table-column>
                <el-table-column prop="phone" label="手机号" ></el-table-column>
                <el-table-column label="操作" width="220" prop="status">
                    <template #default="{row}">
                        <el-button @click="riderUnbind(row)">解绑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分拣员管理部分 -->
        <div class="warehouse-card">
            <div class="section-title">分拣员管理</div>
            <el-form ref="selectedSorter" :model="selectedSorter" label-width="90px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="配置分拣员">
                            <el-input placeholder="请输入分拣员的姓名" v-model="selectedSorter.sorterName">
                                <el-button slot="append" type="primary" @click="querySorterByName">查询</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="text-right">
                        <el-button type="success" @click="dialogFormVisible2 = true">
                            <i class="el-icon-plus"></i> 新增分拣员
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>

            <el-table :data="addSortingList" border stripe>
                <el-table-column prop="sorterName" label="分拣员姓名"></el-table-column>
                <el-table-column prop="phone" label="手机号"></el-table-column>
                <el-table-column label="操作" width="220" prop="status">
                    <template #default="{row}">
                        <el-button @click="sorterUnbind(row)">解绑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="button-group">
            <el-button type="info" @click="cancel">取消</el-button>
            <el-button type="primary" @click="saveUpdateWarehouse">确认修改</el-button>
        </div>

        <!-- 弹窗部分保持不变 -->
        <el-dialog title="新增仓库下的配送员" :visible.sync="dialogFormVisible">
        <el-form :model="selectedCourier">
            <el-form-item label="配送员姓名" :label-width="formLabelWidth">
                <el-select  placeholder="请选择配送员 (姓名 - 电话)" style="width: 60%;" v-model="selectedCourier.id">
                    <el-option
                        v-for="item in courierOptions"
                        :key="item.id"
                        :label="item.courierName + ' - ' +item.phone"
                        :value="item.id">
                        </el-option>
                </el-select>
            </el-form-item>
        </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAddCourier">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="新增仓库下的分拣员" :visible.sync="dialogFormVisible2">
        <el-form :model="selectedSorter">
            <el-form-item label="分拣员姓名" :label-width="formLabelWidth">
                <el-select  placeholder="请选择分拣员 (姓名 - 电话)" style="width: 60%;" v-model="selectedSorter.id">
                    <el-option
                        v-for="item in sorterOptions"
                        :key="item.id"
                        :label="item.sorterName + ' - ' +item.phone"
                        :value="item.id">
                        </el-option>
                </el-select>
            </el-form-item>
        </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="saveAddSorter">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            addRiderList: [],
            addSortingList: [],
            courierOptions: [],
            sorterOptions: [],
             // 城市选项
            cityOptions: [],
            // 区域选项
            districtOptions: [],
            selectedCourier: {  // 存储选中的配送员
                id: '',
                courierName: '',
                phone: ''
            },
            selectedSorter: {  // 存储选中的配送员
                id: '',
                sorterName: '',
                phone: ''
            },
            dialogFormVisible: false,
            dialogFormVisible2: false,
            riderName: '', // 用于绑定骑手查询输入框
            sorterName: '',// // 用于绑定分拣员查询输入框
            formLabelWidth: '120px',
            warehouseDetail: {},
        };
    },
    methods: {
        queryRider() {
        // 查询骑手逻辑
            this.$axios.get('/api/courier/queryRiderList')
            .then(resp => {
                if(resp.data.code == 200){
                    this.courierOptions = resp.data.data;
                }
            });
        },
        querySorter(){
            // 查询分拣员逻辑
            this.$axios.get('/api/sorter/querySorterList')
            .then(resp => {
                if(resp.data.code == 200){
                    this.sorterOptions = resp.data.data;
                }
            });
        },
        saveAddCourier(){
            const params = {
                id: this.selectedCourier.id,
                courierName: this.selectedCourier.courierName,
                phone: this.selectedCourier.phone,
                warehouseId: this.$route.query.id
            };
            this.$axios.post('/api/courier/saveAddCourier', params)
            .then(resp => {
                if(resp.data.code == 200){
                    this.$message.success('添加成功');
                    this.dialogFormVisible = false;
                    
                    //清除下拉框的当前所选数据
                    this.selectedCourier = {  
                        id: '',
                        courierName: '',
                        phone: ''
                    };
                    // 刷新对应的数据
                    this.queryRider();
                    this.queryRiderByCondition();
                }
            });
        },
        saveAddSorter(){
            const sorterParams = {
                id: this.selectedSorter.id,
                sorterName: this.selectedSorter.sorterName,
                phone: this.selectedSorter.phone,
                warehouseId: this.$route.query.id
            };
            this.$axios.post('/api/sorter/saveAddSorter', sorterParams)
            .then(resp => {
                if(resp.data.code == 200){
                    this.$message.success('添加成功');
                    this.dialogFormVisible2 = false;
                    //清除下拉框的当前所选数据
                    this.selectedSorter = {  
                        id: '',
                        sorterName: '',
                        phone: ''
                    }
                    // 刷新对应数据
                    this.querySorter();
                    this.querySorterByCondition();
                }
            })
        },
        queryRiderByCondition(){
            const warehouseId = this.$route.query.id
            this.$axios.get('/api/courier/queryRiderByCondition/'+ warehouseId)
            .then(resp => {
                if(resp.data.code == 200){
                    this.addRiderList = resp.data.data;
                }
            })

        },
        querySorterByCondition(){
            const warehouseId = this.$route.query.id
            this.$axios.get('/api/sorter/querySorterByCondition/'+ warehouseId)
            .then(resp => {
                if(resp.data.code == 200){
                    this.addSortingList = resp.data.data;
                }
            })
        },
        queryRiderByName(){
            const orderParams = {
                courierName: this.selectedCourier.riderName,
                warehouseId: this.$route.query.id
            };
            this.$axios.post('/api/courier/queryRiderByName', orderParams)
            .then(resp => {
                if(resp.data.code == 200){
                    this.addRiderList = resp.data.data;
                }
            })
        },
        querySorterByName(){
            const sorterParams = {
                sorterName: this.selectedSorter.sorterName,
                warehouseId: this.$route.query.id
            };
            this.$axios.post('/api/sorter/querySorterByName', sorterParams)
            .then(resp => {
                if(resp.data.code == 200){
                    this.addSortingList = resp.data.data;
                }
            })
        },
        riderUnbind(row){
            this.$confirm('是否确认解绑该骑手?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/api/courier/riderUnbind/'+ row.id)
                .then(resp => {
                    if(resp.data.code == 200){
                        // 询问是否确认解绑
                            this.$message({
                                type: 'success',
                                message: '解绑成功!'
                            });
                            this.queryRiderByCondition();
                            this.queryRiderByName();
                            this.queryRider();
                    }else {
                        this.$message.error(resp.data.msg || '解绑失败');
                    }
                    }).catch(error => {
                        console.error('解绑失败:', error);
                        this.$message.error('解绑失败，请稍后重试');
                    });
                }).catch(() => {
                    // 用户取消操作
                    this.$message({
                        type: 'info',
                        message: '已取消解绑'
                });
            })   
        },
        sorterUnbind(row){
            this.$confirm('是否确认解绑该分拣员?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/api/sorter/sorterUnbind/'+ row.id)
                .then(resp => {
                    if(resp.data.code == 200){
                        // 询问是否确认解绑
                            this.$message({
                                type: 'success',
                                message: '解绑成功!'
                            });
                            this.querySorterByCondition();
                            this.querySorterByName();
                            this.querySorter();
                    }else {
                        this.$message.error(resp.data.msg || '解绑失败');
                    }
                }).catch(error => {
                    console.error('解绑失败:', error);
                    this.$message.error('解绑失败，请稍后重试');
                });
            }).catch(() => {
                // 用户取消操作
                this.$message({
                    type: 'info',
                    message: '已取消解绑'
                });
            })
        },
            // 获取仓库详情
        // 获取仓库详情
        getWarehouseDetail(warehouseId) {
        this.$axios.get(`/api/warehouse/getWarehouseDetail/${warehouseId}`)
            .then(resp => {
                if (resp.data.code === 200) {
                    this.warehouseDetail = resp.data.data;
                    this.warehouseDetail.cityId = this.warehouseDetail.cityId+"";
                    this.warehouseDetail.districtId = this.warehouseDetail.districtId+"";
                    // 根据城市ID加载对应的区域列表
                    if (this.warehouseDetail.cityId) {
                        // ===========================回显获取区域=========================================
                        if (this.warehouseDetail.cityId) {
                            this.$axios.get(`/api/warehouse/queryDistricts/${this.warehouseDetail.cityId}`)
                                .then(resp => {
                                    if (resp.data.code === 200) {
                                        this.districtOptions = resp.data.data.map(district => ({
                                            label: district.name,
                                            value: district.id + ""
                                        }));
                                    }
                                });
                        } else {
                            this.districtOptions = [];
                        }
                        // ===============================================================================
                    }
                }
            });
        },
        fetchCities(){
            this.$axios.get('/api/warehouse/queryCities')
            .then(resp => {
                if (resp.data.code === 200) {
                    this.cityOptions = resp.data.data.map(city => ({
                        label: city.name,
                        value: city.id + ""
                    }));
                    
                }
            });
        },
        // 城市切换时获取区域列表
        handleCityChange(cityId) {
        this.districtOptions = []; // 清空区域选项
        this.warehouseDetail.districtId = null; // 清空已选的区域
            if (cityId) {
                this.$axios.get(`/api/warehouse/queryDistricts/${cityId}`)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            this.districtOptions = resp.data.data.map(district => ({
                                label: district.name,
                                value: district.id + ""
                            }));
                        }
                    });
            } else {
                this.districtOptions = [];
            }
        },
        cancel() {
            this.$router.push('/warehouseList');
        },
        saveUpdateWarehouse(){
            this.$axios.post('/api/warehouse/updateWarehouse', this.warehouseDetail)
            .then(resp => {
                if (resp.data.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功'
                    });
                    this.$router.push('/warehouseList');
                } else {
                    this.$message.error(resp.data.msg || '修改失败');
                }
            })
        }
    },
    created() {
        const warehouseId = this.$route.query.id
        this.queryRider();
        this.querySorter();
        this.queryRiderByCondition();
        this.querySorterByCondition();
        this.getWarehouseDetail(warehouseId);
        this.fetchCities(); // 新增：获取城市列表
    }
};
</script>

<style scoped>
@import '../styles/warehouse-common.css';

.text-right {
    text-align: right;
    padding-right: 20px;
}

.el-select {
    width: 100%;
}

.el-input {
    width: 100%;
}

.el-table {
    margin-top: 15px;
}

/* 添加一些hover效果 */
.el-button {
    transition: all 0.3s;
}

.el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 自定义表格样式 */
.el-table__header-wrapper th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 500;
}

.el-table__row:hover {
    background-color: #f5f7fa !important;
}

/* 弹窗样式美化 */
.el-dialog {
    border-radius: 8px;
    overflow: hidden;
}

.el-dialog__header {
    background-color: #f5f7fa;
    padding: 15px 20px;
}

.el-dialog__body {
    padding: 30px 20px;
}

.el-dialog__footer {
    border-top: 1px solid #e4e7ed;
    padding: 15px 20px;
}
</style>